package com.windoent.yugioh.ui.fragment.caipangame;

import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.brvah.CaiPanGamesManagerAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.CaiPanGamesListBean;
import com.windoent.yugioh.bean.eventbus.MessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.JumpHelper;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/11 11:50
 * desc   :游戏管理（审核中）
 */
public class CaiPanGameManagerReviewingFragment extends BaseFragment {
    private SmartRefreshLayout mSmartLayout;
    private RecyclerView mRecyclerView;
    private String limit = Constants.PAGETEN;
    private int mCount = 1;
    private String type = "0";//赛的类型：0 全部 1娱乐 2积分 3特殊赛 4 巡回赛
    private String status = "89";//比赛的状态 0全部 89 审核中 2 待参加 3 进行中 8 已结束
    private CaiPanGamesManagerAdapter adapter;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_caipan_game_manager_reviewing;
    }

    public static CaiPanGameManagerReviewingFragment newsInstance() {
        return new CaiPanGameManagerReviewingFragment();
    }

    @Override
    protected void initEventAndData() {
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    private void initView() {
        mSmartLayout = (SmartRefreshLayout) mView.findViewById(R.id.smart_layout);
        mRecyclerView = (RecyclerView) mView.findViewById(R.id.recycler_view);
    }

    private void initData() {
        initAdapter();
    }

    private void initRefreshData(String type, String status) {
        //下拉刷新
        mSmartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                fresh(type, status);
            }
        });
        //加载更多
        mSmartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMore(type, status);
            }
        });
    }

    private void loadMore(String type, String status) {
        mCount = mCount + 1;
        getCaiPanGameList(type, status, mCount + "", limit, false);
    }

    private void fresh(String type, String status) {
        mCount = 1;
        getCaiPanGameList(type, status, mCount + "", limit, true);
    }

    private void initAdapter() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new CaiPanGamesManagerAdapter();
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.recycler_view_empty, mRecyclerView, false));
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> baseQuickAdapter, @NonNull View view, int position) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                List<CaiPanGamesListBean.DataBean.ResBean> data = adapter.getData();
                if (data != null) {
                    CaiPanGamesListBean.DataBean.ResBean matchsBean = data.get(position);
                    if (matchsBean != null) {
                        int id = matchsBean.getId();
                        int rule = matchsBean.getRule();
                        JumpHelper.startGameTab(mContext, id + "", rule + "");
                    }
                }
            }
        });
    }

    //审核中列表
    private void getCaiPanGameList(String type, String status, String page, String limit, boolean fresh) {
        showLoadingDialog("");
        PhoneLive.getCaiPanGameList(getUserToken(), type, status, page, limit, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                ToastUtils.showText(e.getMessage());
                freshFail(fresh);
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            if (BaseUtils.codeIs0(mContext, response)) {
                                CaiPanGamesListBean json = gson.fromJson(response, CaiPanGamesListBean.class);
                                if (json != null) {
                                    CaiPanGamesListBean.DataBean data = json.getData();
                                    if (data != null) {
                                        List<CaiPanGamesListBean.DataBean.ResBean> res = data.getRes();
                                        if (res != null) {
                                            if (fresh) {
                                                adapter.setNewInstance(res);
                                                mSmartLayout.finishRefresh(true);
                                            } else {
                                                adapter.addData(res);
                                                mSmartLayout.finishLoadMore(true);
                                            }
                                        } else freshFail(fresh);
                                    } else freshFail(fresh);
                                } else freshFail(fresh);
                            } else freshFail(fresh);
                        }
                    } catch (JSONException e) {
                        freshFail(fresh);
                        e.printStackTrace();
                    }
                } else {
                    freshFail(fresh);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    //刷新失败
    private void freshFail(boolean fresh) {
        if (fresh) {
            adapter.setNewInstance(null);
            mSmartLayout.finishRefresh(false);
        } else {
            mSmartLayout.finishLoadMore(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent event) {
        String message = event.getMessage();
        int typeInt = event.getType();
        if (typeInt == 1) {
            type = message;
            initRefreshData(type, status);
            fresh(type, status);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //解除注册EventBus
        EventBus.getDefault().unregister(this);
        OkHttpUtils.getInstance().cancelTag(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "侧边栏裁判记录审核中tab");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "侧边栏裁判记录审核中tab");
        }
        initRefreshData(type, status);
        fresh(type, status);
    }
}
